from flask import Blueprint, jsonify, request, current_app
import uuid
import datetime
import jwt
import random

from src.models.tool_models import db, Tool, Calendar, Zodiac, Dream, NameAnalysis
from src.routes.auth import token_required

tool_bp = Blueprint('tool', __name__)

# 获取小工具列表
@tool_bp.route('/list', methods=['GET'])
def get_tool_list():
    tools = Tool.query.filter_by(status=1).all()
    
    tools_list = []
    for tool in tools:
        tools_list.append(tool.to_dict())
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': tools_list,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 万年历查询
@tool_bp.route('/calendar', methods=['GET'])
def query_calendar():
    date_str = request.args.get('date')
    
    if not date_str:
        # 默认查询今天
        date = datetime.date.today()
    else:
        try:
            date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
        except ValueError:
            return jsonify({
                'code': 400,
                'message': '日期格式错误，请使用YYYY-MM-DD格式',
                'data': None,
                'timestamp': datetime.datetime.now().timestamp()
            }), 400
    
    # 查询日历信息
    calendar = Calendar.query.filter_by(solar_date=date).first()
    
    # 如果没有找到记录，创建一个模拟数据（实际应该使用专业库计算）
    if not calendar:
        # 简化处理，实际应使用专业库计算农历日期
        lunar_date = f"{date.year-1911}年{date.month}月{date.day}日"
        
        # 简化处理，实际应使用专业算法计算干支
        gan = "甲乙丙丁戊己庚辛壬癸"[date.year % 10]
        zhi = "子丑寅卯辰巳午未申酉戌亥"[date.year % 12]
        ganzhi_year = f"{gan}{zhi}"
        
        gan = "甲乙丙丁戊己庚辛壬癸"[date.month % 10]
        zhi = "子丑寅卯辰巳午未申酉戌亥"[date.month % 12]
        ganzhi_month = f"{gan}{zhi}"
        
        gan = "甲乙丙丁戊己庚辛壬癸"[date.day % 10]
        zhi = "子丑寅卯辰巳午未申酉戌亥"[date.day % 12]
        ganzhi_day = f"{gan}{zhi}"
        
        # 简化处理，实际应使用专业算法计算生肖
        zodiac = "鼠牛虎兔龙蛇马羊猴鸡狗猪"[date.year % 12]
        
        # 简化处理，实际应使用专业数据判断节气和节日
        solar_term = None
        if date.month == 2 and date.day == 4:
            solar_term = "立春"
        elif date.month == 5 and date.day == 5:
            solar_term = "立夏"
        
        festival = None
        if date.month == 1 and date.day == 1:
            festival = "元旦"
        elif date.month == 5 and date.day == 1:
            festival = "劳动节"
        
        # 简化处理，实际应使用专业数据判断宜忌
        suitable = "出行,会友,谈生意,签约,装修"
        unsuitable = "搬家,动土,开业,结婚"
        
        calendar = Calendar(
            solar_date=date,
            lunar_date=lunar_date,
            ganzhi_year=ganzhi_year,
            ganzhi_month=ganzhi_month,
            ganzhi_day=ganzhi_day,
            zodiac=zodiac,
            solar_term=solar_term,
            festival=festival,
            is_leap_month=0,
            suitable=suitable,
            unsuitable=unsuitable,
            create_time=datetime.datetime.now(),
            update_time=datetime.datetime.now()
        )
        
        try:
            db.session.add(calendar)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            # 忽略错误，继续返回数据
    
    # 构建响应数据
    response_data = {
        'solarDate': date.strftime('%Y-%m-%d'),
        'lunarDate': calendar.lunar_date if calendar else lunar_date,
        'ganzhiYear': calendar.ganzhi_year if calendar else ganzhi_year,
        'ganzhiMonth': calendar.ganzhi_month if calendar else ganzhi_month,
        'ganzhiDay': calendar.ganzhi_day if calendar else ganzhi_day,
        'zodiac': calendar.zodiac if calendar else zodiac,
        'solarTerm': calendar.solar_term if calendar else solar_term,
        'festival': calendar.festival if calendar else festival,
        'isLeapMonth': calendar.is_leap_month if calendar else 0,
        'suitable': calendar.suitable.split(',') if calendar and calendar.suitable else suitable.split(','),
        'unsuitable': calendar.unsuitable.split(',') if calendar and calendar.unsuitable else unsuitable.split(',')
    }
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 星座查询
@tool_bp.route('/constellation', methods=['GET'])
def query_constellation():
    code = request.args.get('code')
    
    if not code:
        # 返回所有星座列表
        constellations = Zodiac.query.filter_by(zodiac_type='constellation').all()
        constellations_list = []
        for constellation in constellations:
            constellations_list.append(constellation.to_dict())
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': constellations_list,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    
    # 查询特定星座
    constellation = Zodiac.query.filter_by(zodiac_type='constellation', zodiac_code=code).first()
    
    if not constellation:
        # 如果没有找到记录，返回错误
        return jsonify({
            'code': 404,
            'message': '未找到相关星座信息',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': constellation.to_dict(),
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 生肖查询
@tool_bp.route('/chinese-zodiac', methods=['GET'])
def query_chinese_zodiac():
    code = request.args.get('code')
    
    if not code:
        # 返回所有生肖列表
        zodiacs = Zodiac.query.filter_by(zodiac_type='chinese_zodiac').all()
        zodiacs_list = []
        for zodiac in zodiacs:
            zodiacs_list.append(zodiac.to_dict())
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': zodiacs_list,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    
    # 查询特定生肖
    zodiac = Zodiac.query.filter_by(zodiac_type='chinese_zodiac', zodiac_code=code).first()
    
    if not zodiac:
        # 如果没有找到记录，返回错误
        return jsonify({
            'code': 404,
            'message': '未找到相关生肖信息',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': zodiac.to_dict(),
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 周公解梦
@tool_bp.route('/dream', methods=['GET'])
def query_dream():
    keyword = request.args.get('keyword')
    
    if not keyword:
        return jsonify({
            'code': 400,
            'message': '请提供关键词',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 查询解梦
    dreams = Dream.query.filter(Dream.keyword.like(f'%{keyword}%')).all()
    
    if not dreams:
        return jsonify({
            'code': 404,
            'message': '未找到相关解梦信息',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    dreams_list = []
    for dream in dreams:
        dreams_list.append(dream.to_dict())
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': dreams_list,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 姓名测算
@tool_bp.route('/name-analysis', methods=['POST'])
def name_analysis():
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('name') or not data.get('gender'):
        return jsonify({
            'code': 400,
            'message': '请提供姓名和性别',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 获取用户ID（如果已登录）
    user_id = None
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 简化处理，实际应使用专业算法计算姓名分数和五行属性
    score = random.randint(70, 95)
    wuxing = "金木水火土"[len(data.get('name')) % 5]
    
    # 付费内容（简化处理）
    fortune = "姓名吉凶分析详细内容，需要付费查看。"
    personality = "性格分析详细内容，需要付费查看。"
    career = "事业分析详细内容，需要付费查看。"
    health = "健康分析详细内容，需要付费查看。"
    suggestion = "建议详细内容，需要付费查看。"
    
    # 创建姓名测算记录
    name_analysis = NameAnalysis(
        name=data.get('name'),
        gender=data.get('gender'),
        score=score,
        wuxing=wuxing,
        fortune=fortune,
        personality=personality,
        career=career,
        health=health,
        suggestion=suggestion,
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    try:
        db.session.add(name_analysis)
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'id': name_analysis.id,
            'name': name_analysis.name,
            'gender': name_analysis.gender,
            'score': name_analysis.score,
            'wuxing': name_analysis.wuxing,
            'basicAnalysis': f"您的姓名为{name_analysis.name}，五行属{name_analysis.wuxing}，总评分为{name_analysis.score}分，属于{'吉名' if name_analysis.score >= 80 else '中等'}。",
            'needPayment': True,
            'paymentInfo': {
                'price': 1.1,
                'memberPrice': 0.1
            }
        }
        
        return jsonify({
            'code': 200,
            'message': '分析成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'分析失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 获取姓名测算详细分析（付费内容）
@tool_bp.route('/name-analysis/<int:analysis_id>/detail', methods=['GET'])
def get_name_analysis_detail(analysis_id):
    # 查询姓名测算
    name_analysis = NameAnalysis.query.get(analysis_id)
    if not name_analysis:
        return jsonify({
            'code': 404,
            'message': '未找到相关姓名测算',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查是否已付费
    # 获取用户ID（如果已登录）
    user_id = None
    is_vip = False
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
            
            # 检查是否是VIP会员
            from src.models.user_models import UserVip
            vip_info = UserVip.query.filter_by(user_id=user_id, status=1).first()
            if vip_info and vip_info.expire_time > datetime.datetime.now():
                is_vip = True
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 如果不是VIP会员，需要付费
    if not is_vip:
        return jsonify({
            'code': 403,
            'message': '需要付费查看详细分析',
            'data': {
                'needPayment': True,
                'paymentInfo': {
                    'price': 1.1,
                    'memberPrice': 0.1
                }
            },
            'timestamp': datetime.datetime.now().timestamp()
        }), 403
    
    # 构建响应数据
    response_data = name_analysis.to_dict(include_paid_content=True)
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200
